/* Copyright 2015 David Overeem (dovereem@cox.net)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * 
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

package org.xtce.apps.editor.ui;

import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import org.omg.space.xtce.HeaderType;
import org.xtce.toolkit.XTCESpaceSystem;

/**
 *
 * @author David Overeem
 *
 */

public class XTCEViewerHistorySet extends javax.swing.JPanel {

    /**
     * Creates new form XTCEViewerHistorySet
     */
    public XTCEViewerHistorySet() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        addHistoryButton = new javax.swing.JButton();
        historyRecordsLabel = new javax.swing.JLabel();
        historyParentPanel = new javax.swing.JPanel();

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/xtce/toolkit/MessagesBundle"); // NOI18N
        addHistoryButton.setText(bundle.getString("tab_ssdetail_addhistory_text")); // NOI18N
        addHistoryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addHistoryButtonActionPerformed(evt);
            }
        });

        historyRecordsLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        historyRecordsLabel.setText(bundle.getString("tab_ssdetail_historylist_text")); // NOI18N

        javax.swing.GroupLayout historyParentPanelLayout = new javax.swing.GroupLayout(historyParentPanel);
        historyParentPanel.setLayout(historyParentPanelLayout);
        historyParentPanelLayout.setHorizontalGroup(
            historyParentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        historyParentPanelLayout.setVerticalGroup(
            historyParentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(historyParentPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 226, Short.MAX_VALUE)
                        .addComponent(addHistoryButton)
                        .addGap(0, 226, Short.MAX_VALUE))
                    .addComponent(historyRecordsLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(historyRecordsLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(historyParentPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(addHistoryButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void addHistoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addHistoryButtonActionPerformed
        addHistoryRecord( "New History Record" );
    }//GEN-LAST:event_addHistoryButtonActionPerformed

    public void setSpaceSystem( XTCESpaceSystem spaceSystem, XTCEViewerSpaceSystemDetails parentScrollPane ) {

        spaceSystem_      = spaceSystem;
        parentScrollPane_ = parentScrollPane;

        HeaderType header = spaceSystem_.getReference().getHeader();
        if ( header != null ) {
            HeaderType.HistorySet records = header.getHistorySet();
            if ( records != null ) {
                recordsListText_.clear();
                recordsListText_.addAll( records.getHistory() );
                makeContentPanel( recordsListText_ );
            }
        }

    }

    public void setEditable( boolean editEnabled ) {
        addHistoryButton.setEnabled( editEnabled );
        Component[] components = historyParentPanel.getComponents();
        for ( Component component : components ) {
            if ( component.getClass() == JPanel.class ) {
                Component[] innerComponents = ((JPanel)component).getComponents();
                for ( Component innerComponent : innerComponents ) {
                    if ( innerComponent.getClass() == XTCEViewerHistory.class ) {
                        ((XTCEViewerHistory)innerComponent).setEditable( editEnabled );
                    }
                }
            }
        }
    }

    public void removeHistoryRecord( int idx ) {
        recordsListText_.remove( idx );
        makeContentPanel( recordsListText_ );
        updateDocument();
    }
    
    public void addHistoryRecord( String newNoteText ) {
        recordsListText_.add( newNoteText );
        makeContentPanel( recordsListText_ );
        updateDocument();
    }

    public void editHistoryRecord( String newNoteText, int idx ) {
        recordsListText_.set( idx, newNoteText );
        updateDocument();
    }

    private void makeContentPanel( List<String> notes ) {

        JPanel notePanel = new JPanel();
        notePanel.setLayout( new BoxLayout( notePanel, BoxLayout.Y_AXIS ) );

        int idx = 0;

        for ( String note : notes ) {
            XTCEViewerHistory record = new XTCEViewerHistory( this, note, idx++ );
            notePanel.add( record );
        }

        historyParentPanel.removeAll();
        historyParentPanel.setLayout( new BoxLayout( historyParentPanel,
                                                     BoxLayout.Y_AXIS ) );
        historyParentPanel.add( notePanel );
        historyParentPanel.revalidate();
        historyParentPanel.repaint();

        parentScrollPane_.sizeChanged();

    }

    private void updateDocument() {

        // ensure that the Header element exists
        HeaderType header = spaceSystem_.getReference().getHeader();
        if ( header == null ) {
            header = new HeaderType();
            spaceSystem_.getReference().setHeader( header );
        }

        // first clear the NoteSet element if there are no notes
        HeaderType.HistorySet records = header.getHistorySet();
        if ( recordsListText_.isEmpty() == true ) {
            if ( records != null ) {
                header.setHistorySet( null );
            }
            return;
        }

        // add a Note element for each one
        if ( records == null ) {
            records = new HeaderType.HistorySet();
            header.setHistorySet( records );
        }
        records.getHistory().clear();
        records.getHistory().addAll( recordsListText_ );

    }

    // Private Data Members

    private XTCESpaceSystem   spaceSystem_      = null;
    private XTCEViewerSpaceSystemDetails            parentScrollPane_ = null;
    private ArrayList<String> recordsListText_  = new ArrayList<>();


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addHistoryButton;
    private javax.swing.JPanel historyParentPanel;
    private javax.swing.JLabel historyRecordsLabel;
    // End of variables declaration//GEN-END:variables
}
